package me.zhengjie.utils;

import org.apache.batik.transcoder.TranscoderException;
import org.apache.batik.transcoder.TranscoderInput;
import org.apache.batik.transcoder.TranscoderOutput;
import org.apache.batik.transcoder.image.PNGTranscoder;
import lombok.extern.slf4j.Slf4j;
import java.io.*;
import java.util.Base64;

@Slf4j
public class FileUtils {
    public static String convertSvgToBase64(String svgContent) {
        try {
            // 检查SVG内容
            if (svgContent == null || svgContent.isEmpty()) {
                throw new IllegalArgumentException("SVG内容为空");
            }
            
            // 确保SVG内容包含命名空间
            if (!svgContent.contains("xmlns=\"http://www.w3.org/2000/svg\"")) {
                svgContent = svgContent.replace("<svg ", "<svg xmlns=\"http://www.w3.org/2000/svg\" ");
            }
            
            // 创建输入流
            ByteArrayInputStream svgStream = new ByteArrayInputStream(svgContent.getBytes("UTF-8"));
            // 创建输出流
            ByteArrayOutputStream pngStream = new ByteArrayOutputStream();
            BufferedOutputStream bufferedPngStream = new BufferedOutputStream(pngStream);
            
            try {
                // 创建转换器
                PNGTranscoder transcoder = new PNGTranscoder();
                transcoder.addTranscodingHint(PNGTranscoder.KEY_WIDTH, 200f);
                transcoder.addTranscodingHint(PNGTranscoder.KEY_HEIGHT, 200f);
                
                // 转换
                TranscoderInput input = new TranscoderInput(svgStream);
                TranscoderOutput output = new TranscoderOutput(bufferedPngStream);
                transcoder.transcode(input, output);
                
                // 刷新并关闭输出流
                bufferedPngStream.flush();
                bufferedPngStream.close();
                
                // 转换为Base64
                byte[] pngData = pngStream.toByteArray();
                return Base64.getEncoder().encodeToString(pngData);
                
            } finally {
                // 关闭所有流
                svgStream.close();
                bufferedPngStream.close();
                pngStream.close();
            }
            
        } catch (IOException | TranscoderException e) {
            log.error("SVG转换失败: {}", e.getMessage(), e);
            throw new RuntimeException("SVG转换失败: " + e.getMessage(), e);
        }
    }
}
